import numpy
from PyQt4 import QtCore
import sys,os,inspect
sys.path.insert(0,os.path.abspath(os.path.join(os.getcwd(), os.pardir)))## add root path 
from KModel.KSingleStock import KSingleStock
from KModel.KSingleStockDataProcessor import KSingleStockDataProcessor as kprocesser
from KModel.KSingleStockCursor import KSingleStockCursor 
from KTrade.KStockFeed import KStockFeed
from KTrade.KPosition import KPosition
import matplotlib.pyplot as plt
import importlib

class KBaseStrategy(QtCore.QObject):
	''' The base class of all trading strategy'''

	def __init__(self,parent,stockfeed):
		QtCore.QObject.__init__(self,parent)
		self.stockfeed=stockfeed
		self.position=KPosition(self)
		self.metrics=[]
		
		# load metrics
		metriclist=['KMetricDrawDown','KMetricSharpRatio','KMetricTrades','KMetricProfit']
		aMod =  importlib.import_module('KTrade.KStrategyMetric.KBaseMetric') #load metric module
		for each_metric in metriclist:
			aClass= getattr(aMod, each_metric) #load class
			self.metrics.append(aClass(self.position))	
			
	def OnStart(self):
		# called before test started
		pass
	def OnFinish(self):
		# call after test exectued
		pass
	
	def OnNewBars(self,curfeedindex):
		# called whenever new bar is generated, barobj is a Series object

		marketdict={}
		closep=self.stockfeed.GetBarByIndex(curfeedindex,'close')
		symbol=self.stockfeed.GetSymbolName()
		
		# update the market price of the holding into a dict
		marketdict[symbol]=closep
		self.position.UpdateEachHoldingValue(marketdict)	
		
		# update all metrics information
		[curmetric.UpdateOnNewBars() for curmetric in self.metrics]
	
		pass
	def GetAllMetrics(self):
		# update all metrics information
		resultdict={}
		[resultdict.update(curmetric.GetMetricData()) for curmetric in self.metrics]
		return resultdict
	
	def run(self):
		# execute the strategy
		# start kfeed until no more data
		# for each_bar in kfeed:
		#    analysizebar
		#    if have orders: add into KOrderTracker
		# see the result
		stockfeed=self.stockfeed
		self.OnStart()
		while stockfeed.HasNextBar():
			stockfeed.MoveForward()
			self.OnNewBars(stockfeed.GetCurrentIndex())		
		self.OnFinish()

		

	
		
